package com.wanganui.utils;

import lombok.experimental.UtilityClass;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author xtwang
 * @des 图片向量工具类
 * @date 2025/3/5 上午11:14
 */
@UtilityClass
public class ImageVectorUtil {

    public float[] getImageVector(MultipartFile file) {
        try {
            // 读取图片文件
            BufferedImage read = ImageIO.read(file.getInputStream());
            // 缩放图片
            BufferedImage bufferedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = bufferedImage.getGraphics();
            graphics.drawImage(read, 0, 0, 100, 100, null);
            graphics.dispose();
            // 转为灰度图
            BufferedImage grayImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
            Graphics2D graphics2D = grayImage.createGraphics();
            graphics2D.drawImage(bufferedImage, 0, 0, null);
            graphics2D.dispose();

            // 提取特征向量 计算每个像素的灰度值
            float[] vector = new float[grayImage.getWidth() * grayImage.getHeight()];
            for (int i = 0; i < grayImage.getWidth(); i++) {
                for (int j = 0; j < grayImage.getHeight(); j++) {
                    int pixel = grayImage.getRGB(i, j);
                    int gray = (pixel >> 16) & 0xFF;
                    vector[j * grayImage.getWidth() + i] = gray;
                }
            }
            return vector;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
